package com.evan.review.ipc;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Process;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;

import com.evan.review.R;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * ContentProvider通信示例
 * 演示如何使用ContentProvider进行进程间通信
 */
public class ContentProviderDemoActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int NOTES_LOADER_ID = 1;
    
    private TextView tvStatus;
    private EditText etTitle;
    private EditText etContent;
    private Button btnAdd;
    private Button btnQuery;
    private Button btnUpdate;
    private Button btnDelete;
    private Button btnLaunchRemote;
    private Button btnShowInfo;
    private TextView tvNotes;
    
    // 当前选中的笔记ID
    private long currentNoteId = -1;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_provider_demo);
        
        // 初始化视图
        initViews();
        // 设置点击监听
        setupListeners();
        // 初始化加载器
        initLoader();
        
        // 显示当前进程ID
        appendStatus("当前进程ID: " + Process.myPid());
    }
    
    private void initViews() {
        tvStatus = findViewById(R.id.tv_provider_status);
        etTitle = findViewById(R.id.et_note_title);
        etContent = findViewById(R.id.et_note_content);
        btnAdd = findViewById(R.id.btn_add_note);
        btnQuery = findViewById(R.id.btn_query_notes);
        btnUpdate = findViewById(R.id.btn_update_note);
        btnDelete = findViewById(R.id.btn_delete_note);
        btnLaunchRemote = findViewById(R.id.btn_launch_remote_process);
        btnShowInfo = findViewById(R.id.btn_provider_info);
        tvNotes = findViewById(R.id.tv_notes_list);
        
        // 初始状态下禁用更新和删除按钮
        btnUpdate.setEnabled(false);
        btnDelete.setEnabled(false);
    }
    
    private void setupListeners() {
        // 添加笔记
        btnAdd.setOnClickListener(v -> addNote());
        
        // 查询笔记
        btnQuery.setOnClickListener(v -> queryNotes());
        
        // 更新笔记
        btnUpdate.setOnClickListener(v -> updateNote());
        
        // 删除笔记
        btnDelete.setOnClickListener(v -> deleteNote());
        
        // 启动远程进程
        btnLaunchRemote.setOnClickListener(v -> launchRemoteProcess());
        
        // 显示ContentProvider介绍
        btnShowInfo.setOnClickListener(v -> showContentProviderInfo());
    }
    
    /**
     * 初始化加载器
     */
    private void initLoader() {
        LoaderManager.getInstance(this).initLoader(NOTES_LOADER_ID, null, this);
    }
    
    /**
     * 添加笔记
     */
    private void addNote() {
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();
        
        if (title.isEmpty()) {
            Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
            return;
        }
        
        ContentValues values = new ContentValues();
        values.put(NoteProvider.COLUMN_TITLE, title);
        values.put(NoteProvider.COLUMN_CONTENT, content);
        values.put(NoteProvider.COLUMN_TIMESTAMP, System.currentTimeMillis());
        
        ContentResolver resolver = getContentResolver();
        Uri uri = resolver.insert(NoteProvider.CONTENT_URI, values);
        
        if (uri != null) {
            appendStatus("添加笔记成功: " + uri);
            clearInputFields();
            // 重新加载数据
            LoaderManager.getInstance(this).restartLoader(NOTES_LOADER_ID, null, this);
        } else {
            appendStatus("添加笔记失败");
        }
    }
    
    /**
     * 查询笔记
     */
    private void queryNotes() {
        // 使用LoaderManager查询，结果在onLoadFinished中处理
        LoaderManager.getInstance(this).restartLoader(NOTES_LOADER_ID, null, this);
        appendStatus("正在查询笔记...");
    }
    
    /**
     * 更新笔记
     */
    private void updateNote() {
        if (currentNoteId == -1) {
            Toast.makeText(this, "请先选择一条笔记", Toast.LENGTH_SHORT).show();
            return;
        }
        
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();
        
        if (title.isEmpty()) {
            Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
            return;
        }
        
        ContentValues values = new ContentValues();
        values.put(NoteProvider.COLUMN_TITLE, title);
        values.put(NoteProvider.COLUMN_CONTENT, content);
        values.put(NoteProvider.COLUMN_TIMESTAMP, System.currentTimeMillis());
        
        Uri noteUri = Uri.withAppendedPath(NoteProvider.CONTENT_URI, String.valueOf(currentNoteId));
        int count = getContentResolver().update(noteUri, values, null, null);
        
        if (count > 0) {
            appendStatus("更新笔记成功: ID=" + currentNoteId);
            clearInputFields();
            currentNoteId = -1;
            btnUpdate.setEnabled(false);
            btnDelete.setEnabled(false);
            // 重新加载数据
            LoaderManager.getInstance(this).restartLoader(NOTES_LOADER_ID, null, this);
        } else {
            appendStatus("更新笔记失败");
        }
    }
    
    /**
     * 删除笔记
     */
    private void deleteNote() {
        if (currentNoteId == -1) {
            Toast.makeText(this, "请先选择一条笔记", Toast.LENGTH_SHORT).show();
            return;
        }
        
        new AlertDialog.Builder(this)
                .setTitle("删除笔记")
                .setMessage("确定要删除这条笔记吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    Uri noteUri = Uri.withAppendedPath(NoteProvider.CONTENT_URI, String.valueOf(currentNoteId));
                    int count = getContentResolver().delete(noteUri, null, null);
                    
                    if (count > 0) {
                        appendStatus("删除笔记成功: ID=" + currentNoteId);
                        clearInputFields();
                        currentNoteId = -1;
                        btnUpdate.setEnabled(false);
                        btnDelete.setEnabled(false);
                        // 重新加载数据
                        LoaderManager.getInstance(this).restartLoader(NOTES_LOADER_ID, null, this);
                    } else {
                        appendStatus("删除笔记失败");
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    /**
     * 启动远程进程
     */
    private void launchRemoteProcess() {
        Intent intent = new Intent(this, RemoteProcessActivity.class);
        intent.putExtra("from_content_provider", true);
        startActivity(intent);
    }
    
    /**
     * 显示ContentProvider介绍对话框
     */
    private void showContentProviderInfo() {
        new AlertDialog.Builder(this)
                .setTitle("ContentProvider介绍")
                .setMessage("ContentProvider是Android中用于不同应用间共享数据的标准接口。\n\n" +
                        "主要特点：\n" +
                        "1. 提供统一的CRUD操作接口\n" +
                        "2. 支持基于URI的数据访问\n" +
                        "3. 内部基于Binder实现跨进程通信\n" +
                        "4. 提供完善的权限控制机制\n\n" +
                        "适用场景：\n" +
                        "- 应用间共享结构化数据\n" +
                        "- 提供系统级数据访问接口\n" +
                        "- 需要细粒度权限控制的数据共享\n\n" +
                        "系统内置ContentProvider：\n" +
                        "- 联系人数据\n" +
                        "- 媒体库\n" +
                        "- 日历数据\n" +
                        "- 通话记录等")
                .setPositiveButton("了解", null)
                .show();
    }
    
    /**
     * 清空输入字段
     */
    private void clearInputFields() {
        etTitle.setText("");
        etContent.setText("");
    }
    
    /**
     * 添加状态信息
     */
    private void appendStatus(String status) {
        String currentText = tvStatus.getText().toString();
        tvStatus.setText((currentText.isEmpty() ? "" : currentText + "\n") + status);
    }
    
    /**
     * 选择笔记进行编辑
     */
    private void selectNote(long id, String title, String content) {
        currentNoteId = id;
        etTitle.setText(title);
        etContent.setText(content);
        btnUpdate.setEnabled(true);
        btnDelete.setEnabled(true);
        appendStatus("已选择笔记: ID=" + id);
    }
    
    @NonNull
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        if (id == NOTES_LOADER_ID) {
            // 创建CursorLoader查询笔记
            return new CursorLoader(
                    this,
                    NoteProvider.CONTENT_URI,
                    null,
                    null,
                    null,
                    NoteProvider.COLUMN_TIMESTAMP + " DESC"
            );
        }
        throw new IllegalArgumentException("Unknown loader id: " + id);
    }
    
    @Override
    public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
        if (loader.getId() == NOTES_LOADER_ID) {
            displayNotes(data);
        }
    }
    
    @Override
    public void onLoaderReset(@NonNull Loader<Cursor> loader) {
        // 清空笔记列表
        tvNotes.setText("暂无笔记");
    }
    
    /**
     * 显示笔记列表
     */
    private void displayNotes(Cursor cursor) {
        if (cursor == null || cursor.getCount() == 0) {
            tvNotes.setText("暂无笔记");
            return;
        }
        
        StringBuilder sb = new StringBuilder();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        
        while (cursor.moveToNext()) {
            long id = cursor.getLong(cursor.getColumnIndexOrThrow(NoteProvider.COLUMN_ID));
            String title = cursor.getString(cursor.getColumnIndexOrThrow(NoteProvider.COLUMN_TITLE));
            String content = cursor.getString(cursor.getColumnIndexOrThrow(NoteProvider.COLUMN_CONTENT));
            long timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(NoteProvider.COLUMN_TIMESTAMP));
            
            String date = dateFormat.format(new Date(timestamp));
            
            sb.append("ID: ").append(id).append("\n");
            sb.append("标题: ").append(title).append("\n");
            sb.append("内容: ").append(content).append("\n");
            sb.append("时间: ").append(date).append("\n");
            sb.append("点击编辑: [ID=").append(id).append("]\n\n");
        }
        
        tvNotes.setText(sb.toString());
        
        // 设置点击事件，选择笔记进行编辑
        tvNotes.setOnClickListener(v -> {
            String text = tvNotes.getText().toString();
            int startIndex = text.indexOf("[ID=");
            if (startIndex != -1) {
                int endIndex = text.indexOf("]", startIndex);
                if (endIndex != -1) {
                    String idStr = text.substring(startIndex + 4, endIndex);
                    try {
                        long noteId = Long.parseLong(idStr);
                        // 查询选中的笔记
                        Uri noteUri = Uri.withAppendedPath(NoteProvider.CONTENT_URI, String.valueOf(noteId));
                        Cursor noteCursor = getContentResolver().query(noteUri, null, null, null, null);
                        
                        if (noteCursor != null && noteCursor.moveToFirst()) {
                            String title = noteCursor.getString(noteCursor.getColumnIndexOrThrow(NoteProvider.COLUMN_TITLE));
                            String content = noteCursor.getString(noteCursor.getColumnIndexOrThrow(NoteProvider.COLUMN_CONTENT));
                            selectNote(noteId, title, content);
                            noteCursor.close();
                        }
                    } catch (NumberFormatException e) {
                        Toast.makeText(this, "解析ID失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        
        appendStatus("查询到 " + cursor.getCount() + " 条笔记");
    }
} 